package com.njtoyo.taxi.admin.rest.readfile.taxis;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.njtoyo.taxi.admin.library.common.util.CopyUtil;
import com.njtoyo.taxi.admin.logic.business.TaxisLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.Taxi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class ScrapBatchListener extends AnalysisEventListener<ScrapBatchData> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ScrapBatchListener.class);

    private final ScrapBatcResult result = new ScrapBatcResult();
    private final TaxisLogic registerBatchLogic;
    private final List<Taxi> successResult = new ArrayList<>();
    private final List<ScrapBatcResult.FailData> failResult = new ArrayList<>();

    public ScrapBatchListener(TaxisLogic registerBatchLogic) {
        this.registerBatchLogic = registerBatchLogic;
    }

    @Override
    public void invoke(ScrapBatchData ScrapBatchData, AnalysisContext analysisContext) {
        this.result.setUploadCount(this.result.getUploadCount() + 1);
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(ScrapBatchData));
        try {
            Long id = ScrapBatchData.getId();
            Taxi taxi = registerBatchLogic.scrapBatch(id, true);
            this.successResult.add(taxi);
            this.result.setSuccessCount(this.result.getSuccessCount() + 1);
        } catch (Exception e) {
            ScrapBatcResult.FailData failData = CopyUtil.copy(ScrapBatchData, ScrapBatcResult.FailData.class);
            failData.setMessage(e.getMessage());
            this.failResult.add(failData);
            this.result.setFailCount(this.result.getFailCount() + 1);
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        this.result.setSuccessResult(this.successResult);
        this.result.setFailResult(this.failResult);
    }

    public ScrapBatcResult getResult() {
        return result;
    }
}